#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Web界面
Web Interface for AI Content Reliability Detection System

使用Flask框架提供Web界面
"""

from flask import Flask, render_template, request, jsonify, session
import os
import json
from datetime import datetime
import logging
import tempfile
from werkzeug.utils import secure_filename

# 导入我们的模块
from ai_content_detector import ContentReliabilitySystem, ContentAnalysis
from rag_knowledge_base import KnowledgeBaseManager
from document_processor import DocumentProcessor
from source_extractor import SourceExtractor
from url_content_analyzer import URLContentAnalyzer
from zerogpt_detector import ZerogptDetector
from config import Config

app = Flask(__name__)
app.secret_key = 'ai_detector_secret_key_2024'

# 初始化系统
api_keys = Config.get_api_keys()
system = ContentReliabilitySystem(api_keys)
kb_manager = KnowledgeBaseManager()
doc_processor = DocumentProcessor()
source_extractor = SourceExtractor()
url_analyzer = URLContentAnalyzer()
zerogpt_detector = ZerogptDetector()

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

@app.route('/')
def index():
    """主页"""
    return render_template('index.html')

@app.route('/api/detect', methods=['POST'])
def detect_content():
    """API端点：检测内容"""
    try:
        data = request.get_json()
        content = data.get('content', '')
        sources = data.get('sources', [])
        
        if not content:
            return jsonify({'error': '内容不能为空'}), 400
        
        # 处理内容
        result = system.process_content(content, sources)
        
        # 转换为JSON可序列化的格式
        response = {
            'ai_probability': result.ai_probability,
            'content_type': result.content_type.value,
            'reliability_score': result.reliability_score,
            'filtered_content': result.filtered_content,
            'removed_sections': result.removed_sections,
            'verification_result': result.verification_result,
            'extracted_sources': result.verification_result.get('extracted_sources', {}),
            'timestamp': datetime.now().isoformat()
        }
        
        return jsonify(response)
        
    except Exception as e:
        logger.error(f"检测内容时出错: {str(e)}")
        return jsonify({'error': f'处理失败: {str(e)}'}), 500

@app.route('/api/detect/document', methods=['POST'])
def detect_document():
    """API端点：检测文档文件"""
    try:
        if 'file' not in request.files:
            return jsonify({'error': '没有上传文件'}), 400
        
        file = request.files['file']
        if file.filename == '':
            return jsonify({'error': '没有选择文件'}), 400
        
        # 保存上传的文件到临时目录
        with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.filename)[1]) as tmp_file:
            file.save(tmp_file.name)
            file_path = tmp_file.name
        
        try:
            # 处理文档
            doc_result = doc_processor.process_document(file_path)
            
            if not doc_result['success']:
                return jsonify({
                    'error': doc_result['error'],
                    'supported_formats': doc_processor.get_supported_formats()
                }), 400
            
            # 获取文档摘要
            summary = doc_processor.get_document_summary(doc_result['content'])
            
            # 检测文档内容
            result = system.process_content(doc_result['content'], [])
            
            # 转换为JSON可序列化的格式
            response = {
                'ai_probability': result.ai_probability,
                'content_type': result.content_type.value,
                'reliability_score': result.reliability_score,
                'filtered_content': result.filtered_content,
                'removed_sections': result.removed_sections,
                'verification_result': result.verification_result,
                'document_info': {
                    'filename': file.filename,
                    'file_size': doc_result['file_size'],
                    'file_type': doc_result['file_type'],
                    'word_count': doc_result['word_count'],
                    'summary': summary
                },
                'timestamp': datetime.now().isoformat()
            }
            
            return jsonify(response)
            
        finally:
            # 清理临时文件
            try:
                os.unlink(file_path)
            except:
                pass
        
    except Exception as e:
        logger.error(f"检测文档时出错: {str(e)}")
        return jsonify({'error': f'处理失败: {str(e)}'}), 500

@app.route('/api/document/formats', methods=['GET'])
def get_supported_formats():
    """API端点：获取支持的文件格式"""
    try:
        formats = doc_processor.get_supported_formats()
        return jsonify({
            'supported_formats': formats,
            'count': len(formats)
        })
    except Exception as e:
        logger.error(f"获取支持格式时出错: {str(e)}")
        return jsonify({'error': f'获取失败: {str(e)}'}), 500

@app.route('/api/verify', methods=['POST'])
def verify_information():
    """API端点：验证信息"""
    try:
        data = request.get_json()
        claim = data.get('claim', '')
        
        if not claim:
            return jsonify({'error': '声明不能为空'}), 400
        
        # 验证信息
        result = kb_manager.verify_information(claim)
        
        return jsonify({
            'claim': claim,
            'verification_result': result,
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        logger.error(f"验证信息时出错: {str(e)}")
        return jsonify({'error': f'验证失败: {str(e)}'}), 500

@app.route('/api/knowledge/add', methods=['POST'])
def add_knowledge():
    """API端点：添加知识库条目"""
    try:
        data = request.get_json()
        title = data.get('title', '')
        content = data.get('content', '')
        source = data.get('source', '')
        source_type = data.get('source_type', 'academic')
        reliability_score = data.get('reliability_score', 0.8)
        
        if not all([title, content, source]):
            return jsonify({'error': '标题、内容和来源都是必需的'}), 400
        
        # 添加到知识库
        success = kb_manager.add_knowledge_entry(
            title=title,
            content=content,
            source=source,
            source_type=source_type,
            reliability_score=reliability_score
        )
        
        if success:
            return jsonify({
                'success': True,
                'message': '成功添加到知识库',
                'timestamp': datetime.now().isoformat()
            })
        else:
            return jsonify({'error': '添加失败'}), 500
            
    except Exception as e:
        logger.error(f"添加知识库条目时出错: {str(e)}")
        return jsonify({'error': f'添加失败: {str(e)}'}), 500

@app.route('/api/knowledge/search', methods=['POST'])
def search_knowledge():
    """API端点：搜索知识库"""
    try:
        data = request.get_json()
        query = data.get('query', '')
        limit = data.get('limit', 10)
        
        if not query:
            return jsonify({'error': '搜索查询不能为空'}), 400
        
        # 搜索知识库
        results = kb_manager.search_knowledge(query, limit)
        
        return jsonify({
            'query': query,
            'results': [entry.to_dict() for entry in results],
            'count': len(results),
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        logger.error(f"搜索知识库时出错: {str(e)}")
        return jsonify({'error': f'搜索失败: {str(e)}'}), 500

@app.route('/api/knowledge/stats')
def get_knowledge_stats():
    """API端点：获取知识库统计信息"""
    try:
        stats = kb_manager.get_knowledge_stats()
        
        return jsonify({
            'stats': stats,
            'timestamp': datetime.now().isoformat()
        })
        
    except Exception as e:
        logger.error(f"获取知识库统计信息时出错: {str(e)}")
        return jsonify({'error': f'获取统计信息失败: {str(e)}'}), 500

@app.route('/api/analyze/url', methods=['POST'])
def analyze_url_content():
    """API端点：分析URL内容"""
    try:
        data = request.get_json()
        url = data.get('url', '')
        
        if not url:
            return jsonify({'error': 'URL不能为空'}), 400
        
        # 分析URL内容
        result = url_analyzer.analyze_url_content(url)
        
        return jsonify(result)
        
    except Exception as e:
        logger.error(f"分析URL内容时出错: {str(e)}")
        return jsonify({'error': f'分析失败: {str(e)}'}), 500

@app.route('/api/extract/sources', methods=['POST'])
def extract_sources():
    """API端点：提取信息来源"""
    try:
        data = request.get_json()
        content = data.get('content', '')

        if not content:
            return jsonify({'error': '内容不能为空'}), 400

        # 提取信息来源
        sources = source_extractor.extract_sources(content)

        return jsonify(sources)

    except Exception as e:
        logger.error(f"提取信息来源时出错: {str(e)}")
        return jsonify({'error': f'提取失败: {str(e)}'}), 500

@app.route('/api/detect/ai', methods=['POST'])
def detect_ai_content():
    """API端点：检测AI生成内容"""
    try:
        data = request.get_json()
        content = data.get('content', '')

        if not content:
            return jsonify({'error': '内容不能为空'}), 400

        # 使用Zerogpt检测器检测AI内容
        result = zerogpt_detector.detect_ai_content(content)

        # 添加时间戳
        result['timestamp'] = datetime.now().isoformat()

        return jsonify(result)

    except Exception as e:
        logger.error(f"AI内容检测时出错: {str(e)}")
        return jsonify({'error': f'检测失败: {str(e)}'}), 500

@app.route('/api/detect/ai/batch', methods=['POST'])
def batch_detect_ai_content():
    """API端点：批量检测AI生成内容"""
    try:
        data = request.get_json()
        contents = data.get('contents', [])

        if not contents:
            return jsonify({'error': '内容列表不能为空'}), 400

        if not isinstance(contents, list):
            return jsonify({'error': '内容必须是列表格式'}), 400

        # 批量检测
        results = zerogpt_detector.batch_detect(contents)
        
        # 获取统计信息
        stats = zerogpt_detector.get_detection_stats(results)

        response = {
            'results': results,
            'statistics': stats,
            'timestamp': datetime.now().isoformat()
        }

        return jsonify(response)

    except Exception as e:
        logger.error(f"批量AI内容检测时出错: {str(e)}")
        return jsonify({'error': f'批量检测失败: {str(e)}'}), 500

@app.route('/demo')
def demo():
    """演示页面"""
    return render_template('demo.html')

if __name__ == '__main__':
    print("=== AI内容可靠性检测系统 Web界面 ===")
    print("启动Web服务器...")
    print("访问地址: http://localhost:5000")
    print("演示页面: http://localhost:5000/demo")
    
    # 启动Flask应用
    app.run(debug=True, host='0.0.0.0', port=5000) 